package com.edu.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.study.entities.RPage;
import com.edu.study.entities.po.EduWordLearnNew;
import com.edu.study.entities.po.EduWordLibrary;
import com.edu.study.entities.vo.EduWordLibraryVO;
import com.edu.study.mapper.EduWordMapper;
import com.edu.study.service.EduWordLearnNewService;
import com.edu.study.service.EduWordService;
import com.edu.utils.UserContextUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.model.AppLoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class EduWordServiceImpl extends ServiceImpl<EduWordMapper, EduWordLibrary> implements EduWordService {

  @Autowired
  EduWordLearnNewService eduWordLearnService;

  @Autowired
  EduWordService eduWordService;

  private RPage getUserWords(int pageNum, int pageSize, String wordSource) {
    AppLoginUser user = UserContextUtil.currentUser(); // ✅ 只声明一次

    // 公共查询逻辑
    QueryWrapper<EduWordLearnNew> learnQuery = new QueryWrapper<>();
    learnQuery.eq("member_id", user.getId())
        .eq("word_source", wordSource) // 差异点参数化
        .nested(wrapper ->
            wrapper.ne("del_flag", "1")
                .or()
                .isNull("del_flag")
        );

    // 分页逻辑
    PageInfo<EduWordLearnNew> pageInfo = PageHelper.startPage(pageNum, pageSize, "create_date")
        .doSelectPageInfo(() -> eduWordLearnService.list(learnQuery));

    List<EduWordLearnNew> learnList = pageInfo.getList();
    List<String> wordIds = learnList.stream()
        .map(EduWordLearnNew::getWordId)
        .collect(Collectors.toList());

    if (ObjectUtils.isEmpty(wordIds)) {
      return RPage.of(pageInfo, "没有单词");
    }

    // 单词查询逻辑
    QueryWrapper<EduWordLibrary> wordQuery = new QueryWrapper<>();
    wordQuery.isNotNull("word")
        .ne("word", "")
        .notLike("word", " ")
        .nested(wrapper ->
            wrapper.ne("del_flag", "1")
                .or()
                .isNull("del_flag")
        )
        .in("id", wordIds);

    List<EduWordLibrary> result = eduWordService.list(wordQuery);
    List<EduWordLibraryVO> voList = new ArrayList<>();

    // 出于性能考虑，避免在循环内部使用stream检索，提前建立映射
    Map<String, EduWordLearnNew> learnMap = learnList.stream()
        .collect(Collectors.toMap(EduWordLearnNew::getWordId, Function.identity()));

    List<EduWordLibraryVO> voResult = result.stream()
        .map(word -> {
          EduWordLibraryVO vo = new EduWordLibraryVO();
          BeanUtils.copyProperties(word, vo);

          EduWordLearnNew wordLearn = learnMap.get(vo.getId());
          if (wordLearn != null) {
            vo.setKo(wordLearn.getKo()).setKoDate(wordLearn.getKoDate());
          }
          return vo;
        })
        .collect(Collectors.toList());

    RPage<EduWordLibraryVO> page = RPage.of(pageInfo, "", voResult);

    return page;
  }



  @Override
  public RPage<EduWordLibraryVO> getUserCourseWords(int pageNum, int pageSize) {
    return getUserWords(pageNum, pageSize, "1");
  }

  @Override
  public RPage<EduWordLibraryVO> getUserBookWords(int pageNum, int pageSize) {
    return getUserWords(pageNum, pageSize, "2");
  }
}
